import 'package:flutter/foundation.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:just_audio/just_audio.dart';
import 'package:record/record.dart';
// import 'record_amr/record_amr.dart';

class ChatVoicePlayer extends ChangeNotifier {
  String currentMsgId = '';
  bool isPlaying = false;
  final player = AudioPlayer();
  ChatVoicePlayer() {
    player.playerStateStream.listen((state) {
      if (state.processingState == ProcessingState.completed) {
        isPlaying = false;

        currentMsgId = '';
      } else if (state.processingState == ProcessingState.buffering) {
        isPlaying = true;
      }
      notifyListeners();
    });
  }
  playVoice(EMMessage msg) async {
    if (currentMsgId.isNotEmpty) {
      isPlaying = false;
      notifyListeners();
      currentMsgId = '';
    }
    currentMsgId = msg.msgId ?? '';
    EMVoiceMessageBody body = msg.body as EMVoiceMessageBody;
    await player.setFilePath(body.localPath ?? '');
    player.play();
  }

  stopPlay() async {
    if (currentMsgId.isNotEmpty) {
      isPlaying = false;
      notifyListeners();
      currentMsgId = '';
    }
    player.stop();
  }

  @override
  void dispose() {
    player.dispose();
    super.dispose();
  }
}
